package com.learn.concurrent.itcast.thread.demo;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreMutex {

    private static final int THREAD_COUNT=30;

    //初始化为5,互斥信号量
    private static final  Semaphore mutex=new Semaphore(5);

    public static void main(String[] args) {
        ExecutorService pools= Executors.newFixedThreadPool(THREAD_COUNT);

        for (int i=0 ; i < THREAD_COUNT;i++){
            final int index = i;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        mutex.acquire();
                        System.out.println(String.format("[Thread-%s]抢到锁，任务id --- %s--%s",Thread.currentThread().getId(),index, LocalDateTime.now()));
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        //使用完成释放锁
                        mutex.release();
                        System.out.println(String.format("[Thread-%s]释放锁",Thread.currentThread().getId()));
                    }
                }
            };
            pools.execute(run);
        }
        pools.shutdown();
    }
}
